package com.ddxcloud.common.sms.utils;

import cn.hutool.json.JSONUtil;
import com.ddxcloud.common.sms.config.SmsConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@Component
@Slf4j
public class SmsUtil {

    @Resource
    SmsConfig smsConfig;

    public void sendMsg(String phone, String content) throws IOException {
        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod(smsConfig.getUrl());
        post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
        NameValuePair[] data = {
                new NameValuePair("username", smsConfig.getUsername()),
                new NameValuePair("passwd", smsConfig.getPassword()),
                new NameValuePair("phone", phone),
                new NameValuePair("msg", smsConfig.getSignName() + content),
                new NameValuePair("needstatus", smsConfig.getNeedStatus())
        };
        log.info("request params: {}", JSONUtil.toJsonStr(data));
        post.setRequestBody(data);
        client.executeMethod(post);
        log.info("response params: {}", post.getResponseBodyAsString());
    }
}
